import React from 'react';
import { connect } from 'react-redux';
import { API_HOST } from 'Constants/config';
import EditVideoModal from './Modal';
import CommonBorder from './../../../DispatchPage/Components/CommonBorder';
import './index.scss';

class MaxOnce extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectTab: 1,
      recordData: '',
      isVideo: false,
      videoId: props.params.id,
      socktAuth: props.userSocketAuth,
      userId: props.userId,
      record: '',
    };
    this.handleModalOk = ::this.handleModalOk;
    this.handleStop = ::this.handleStop;
    this.initVideo = ::this.initVideo;
    this.initConnect = ::this.initConnect;
    this.handleModalCancel = ::this.handleModalCancel;
  }
  componentDidMount() {
    this.initConnect();
  }
  componentWillUnmount() {
    this.handleStop();
    this.stompClient.disconnect();
  }

  handleStop() {
    if (this.localStream && this.client && this.stompClient) {
      this.localStream.stop();
      this.localStream.close();
      this.client.unpublish(this.localStream);
      this.client.unsubscribe(window.remoteStream);
      AdapterJS.attachMediaStream(document.getElementById('otherVideo'), null);
      AdapterJS.attachMediaStream(document.getElementById('selfVideo'), null);
    }
    this.setState({
      isVideo: false,
    });
    sessionStorage.removeItem('channelKey');
    sessionStorage.removeItem('chatId');
  }
  initConnect() {
    const { socktAuth, userId } = this.state;
    const self = this;
    const socket = new SockJS(`${API_HOST}/gs-guide-websocket?socket_auth=${socktAuth}`);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, () => {
      this.stompClient.subscribe(`/topic/user.${userId}/chat`, (res) => {
        if (JSON.parse(res.body).type === 'chat_req') {
          this.form.showModal();
          this.setState({
            record: JSON.parse(res.body),
          });
        } else if (JSON.parse(res.body).type === 'chat_req_result') {
          self.initVideo(JSON.parse(res.body).channelKey, JSON.parse(res.body).chatId);
          sessionStorage.setItem('channelKey', JSON.parse(res.body).channelKey);
          sessionStorage.setItem('chatId', JSON.parse(res.body).chatId);
        }
      });
    });
  }
  initVideo(key, chatId) {
    // 创建客户端
    const that = this;
    this.client = AgoraRTC.createClient();
    // 初始化客户端
    this.client.init('1dd11fffa0ac413b961dd185712f9fdc', () => {
      // 加入频道
      this.client.join(key, chatId, parseInt(that.state.userId, 10), () => {
        // 创建音视频流对象
        this.localStream = AgoraRTC.createStream({
          streamID: that.state.userId,
          audio: true,
          video: true,
          screen: false,
        });
        window.localStream = this.localStream;
        //this.localStream.setVideoProfile('360P_8');
        // 初始化音视频流对象
        this.localStream.init(() => {
          // 播放本地视频流
          console.log('this.localStream.stream2', this.localStream.stream);
          window.stream = this.localStream.stream;
          console.log('enter');
          AdapterJS.attachMediaStream(document.getElementById('selfVideo'), window.stream);
          console.log('wait to attach local stream');
          console.log('end');
          //this.localStream.play('selfVideo', '/images');

          // 将本地的视频流上传到服务器
          this.client.publish(this.localStream, () => {
            // console.log('publish is err', err);
          });
        }, () => {
          // console.log(err);
        });
        // 通知应用程序远程视频流已经添加
        this.client.on('stream-added', (evt) => {
          console.log('stream-added', evt);
          const stream = evt.stream;
          window.remoteStream = stream;
          // 订阅远程视频流
          this.client.subscribe(stream, () => {
            // console.log('subscribe stream failed', err);
          });
        });
        // 接收远程视频流
        this.client.on('stream-subscribed', (evt) => {
          const otherStream = evt.stream;
          //otherStream.play('otherVideo', '/images');
          AdapterJS.attachMediaStream(document.getElementById('otherVideo'), otherStream.stream);
        });
        // 远程音视频流已删除回调事件
        this.client.on('stream-removed', () => {
          // const stream = evt.stream;
          this.handleStop();
        });
        //通知对方已离开会议室
        this.client.on('peer-leave', () => {
          console.log('leave');
          this.handleStop();
        });
      });
    }, (err) => {
      console.log(err);
    });
  }
  handleModalOk() {
    const { record } = this.state;
    this.stompClient.send('/app/chat/opinion', {}, JSON.stringify({ type: 'chat_opinion', chatId: `${record.chatId}`, agree: '1' }));
    this.setState({
      isVideo: true,
    }, () => {
      document.getElementById('otherVideo').style.width = `${document.getElementById('direct-warp').offsetWidth}px`;
    });
  }
  handleModalCancel() {
    const { record } = this.state;
    this.stompClient.send('/app/chat/opinion', {}, JSON.stringify({ type: 'chat_opinion', chatId: `${record.chatId}`, agree: '2' }));
  }
  render() {
    const { isVideo } = this.state;
    return (
      <CommonBorder
        content={
          <div className="supervise-wrap">
            {
              !isVideo &&
              <div className="supervise-content">
                <div>
                  暂无视频请求...
                </div>
              </div>
            }
            {
              isVideo &&
              <div className="video-link-wrap">
                <div className="video-linking" id="direct-warp">
                  <video id="otherVideo" className="other-video" />
                  <video id="selfVideo" className="self-video" />
                  <img src="images/icon_video_stop.png" alt="挂断视频" className="stop-video" onClick={this.handleStop.bind(this)} />
                </div>
              </div>
            }
            <EditVideoModal
              ref={(ref) => { this.form = ref; }}
              handleModalOk={this.handleModalOk.bind(this)}
              handModalCancel={this.handleModalCancel.bind(this)}
            />
          </div>
        }
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.userReducer,
  };
}

export default connect(mapStateToProps)(MaxOnce);

